﻿package crochet.core.policy;

/*
 Copyright 2011 Intuitive Solutions

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import crochet.core.IExceptionHandlerDelegate;
import crochet.core.IScheduler;
import crochet.core.ISchedulerDelegate;

public class RetryOnExceptionExecutionPolicy extends BaseExecutionPolicy {
	protected boolean bForceThrow;
	protected int iRetries, iDelay;

	public RetryOnExceptionExecutionPolicy(int iRetries, int iDelay,
			boolean bForceThrow) {
		this(null, null, null, iRetries, iDelay, bForceThrow);
	}

	public RetryOnExceptionExecutionPolicy(IScheduler sRootScheduler,
			ISchedulerDelegate sdSchedulerProcess,
			IExceptionHandlerDelegate ehdExceptionHandlerDelegate,
			int iRetries, int iDelay, boolean bForceThrow) {
		super(sRootScheduler, sdSchedulerProcess, ehdExceptionHandlerDelegate);
		this.iDelay = iDelay;
		this.iRetries = iRetries;
		this.bForceThrow = bForceThrow;
	}

	@Override
	public void execute(IScheduler sSourceScheduler) throws Exception {
		for (int i = 0; i < iRetries; ++i) {
			try {
				sdSchedulerProcess.execute(sSourceScheduler);
				break;
			} catch (Exception eException) {
				if (i >= (iRetries - 1)) {
					if (ehdExceptionHandlerDelegate != null) {
						ehdExceptionHandlerDelegate.handle(eException);
					}

					if (bForceThrow) {
						throw eException;
					}
				}
			}

			if (iDelay > 0) {
				Thread.sleep(iDelay);
			}
		}
	}

	@Override
	public IExecutionPolicy clone(ISchedulerDelegate sdSchedulerProcess,
			IExceptionHandlerDelegate ehdExceptionHandlerDelegate) {
		RetryOnExceptionExecutionPolicy depNewPolicy = new RetryOnExceptionExecutionPolicy(
				sRootScheduler, sdSchedulerProcess,
				ehdExceptionHandlerDelegate, iRetries, iDelay, bForceThrow);

		return depNewPolicy;
	}
}
